import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:myapp/models/models.dart';

import '../../repositories/repositories.dart';

part 'profile_event.dart';
part 'profile_state.dart';

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  final UserRepository userRepository;
  ProfileBloc({
    required this.userRepository
  }) : super(ProfileInitial()) {
    on<LoadProfileEvent>((event, emit) async {
      emit(ProfileLoading());
      try {
        var user= await userRepository.getUser(event.userId);
        emit(ProfileLoaded(profile: user.profile));
      } catch (e) {
        emit(ProfileError( error: e));
      }
    });
    on<ToggleFollowUserEvent>((event, emit) async {
      emit(ProfileLoading());
      try {
        var user= await userRepository.getUser(event.userId);
        var profile=user.profile;
        if (profile.following.isNotEmpty){
          await userRepository.unFollowUser(event.userId);
        } else{
          await userRepository.followUser(event.userId);
        }
        emit(ProfileLoaded(profile: user.profile));
      } catch (e) {
        emit(ProfileError( error: e));
      }
    });
  }
}
